package com.imooc.service.impl;

import com.imooc.constants.RedisConstant;
import com.imooc.dataobject.ProductInfo;
import com.imooc.dto.CartDTO;
import com.imooc.enums.ProductStatusEnum;
import com.imooc.enums.ResultEnum;
import com.imooc.exception.SellException;
import com.imooc.repository.ProductInfoRepository;
import com.imooc.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * FileName: ProductServiceImpl.java
 * Description: ProductServiceImpl
 *
 * @author HuangRI(874668739 @ qq.com)
 * @version 1.0
 * @date 2020/12/16
 */
@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductInfoRepository productInfoRepository;

    // 缓存方式2-1
//    @Cacheable(cacheNames = RedisConstant.CACHE_BUYER_PRODUCT_UP_LIST, key = RedisConstant.KEY_BUYER_PRODUCT)
    @Override
    public ProductInfo findOne(String productId) {
        Optional<ProductInfo> optionalProductInfo = this.productInfoRepository.findById(productId);
        return optionalProductInfo.isPresent() ? optionalProductInfo.get() : null;
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return this.productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return this.productInfoRepository.findAll(pageable);
    }

    // 缓存方式1-2
//    @CachePut(cacheNames = RedisConstant.CACHE_BUYER_PRODUCT_UP_LIST, key = RedisConstant.KEY_BUYER_PRODUCT)
    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return this.productInfoRepository.save(productInfo);
    }

    /**
     * TODO 使用redis的分布式锁解决超卖问题
     * @param cartDTOs List<CartDTO>
     */
    @Override
    @Transactional
    public void increaseStock(List<CartDTO> cartDTOs) {
        log.info("加库存, cartDTOs={}", cartDTOs);
        cartDTOs.forEach(cartDTO -> {
            Optional<ProductInfo> optionalProductInfo = this.productInfoRepository.findById(cartDTO.getProductId());
            if (!optionalProductInfo.isPresent()) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            ProductInfo productInfo = optionalProductInfo.get();
            Integer updateStock = productInfo.getProductStock() + cartDTO.getProductQuantity();
            productInfo.setProductStock(updateStock);
        });
    }

    /**
     * TODO 使用redis的分布式锁解决超卖问题
     * @param cartDTOs List<CartDTO>
     */
    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> cartDTOs) {
        log.info("减库存, cartDTOs={}", cartDTOs);
        cartDTOs.forEach(cartDTO -> {
            Optional<ProductInfo> productInfoOptional = this.productInfoRepository.findById(cartDTO.getProductId());
            if (!productInfoOptional.isPresent()) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            ProductInfo productInfo = productInfoOptional.get();
            Integer productStock = productInfo.getProductStock() - cartDTO.getProductQuantity();
            if (productStock < 0) {
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            productInfo.setProductStock(productStock);
            this.productInfoRepository.save(productInfo);
        });
    }

    @Override
    public ProductInfo onSale(String productId) {
        log.info("【商品上架】productId={}", productId);
        Optional<ProductInfo> productInfoOptional = this.productInfoRepository.findById(productId);
        if (!productInfoOptional.isPresent()) {
            log.error("【商品上架】查找不到商品，productId={}", productId);
            throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
        }

        ProductInfo productInfo = productInfoOptional.get();
        // 判断商品状态是否为下架
        if (!ProductStatusEnum.DOWN.getCode().equals(productInfo.getProductStatus())) {
            log.error("【商品上架】商品状态有误，productInfo={}", productInfo);
            throw new SellException(ResultEnum.PRODUCT_STATUS_ERROR);
        }
        // 上架商品
        productInfo.setProductStatus(ProductStatusEnum.UP.getCode());
        ProductInfo result = this.productInfoRepository.save(productInfo);
        if (null == result) {
            log.error("【商品上架】上架商品失败，productInfo={}", productInfo);
            throw new SellException(ResultEnum.PRODUCT_UPDATE_FAIL);
        }
        return productInfo;
    }

    @Override
    public ProductInfo offSale(String productId) {
        log.info("【商品下架】productId={}", productId);
        Optional<ProductInfo> productInfoOptional = this.productInfoRepository.findById(productId);
        if (!productInfoOptional.isPresent()) {
            log.error("【商品下架】查找不到商品，productId={}", productId);
            throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
        }

        ProductInfo productInfo = productInfoOptional.get();
        // 判断商品状态是否为下架
        if (!ProductStatusEnum.UP.getCode().equals(productInfo.getProductStatus())) {
            log.error("【商品下架】商品状态有误，productInfo={}", productInfo);
            throw new SellException(ResultEnum.PRODUCT_STATUS_ERROR);
        }
        // 上架商品
        productInfo.setProductStatus(ProductStatusEnum.DOWN.getCode());
        ProductInfo result = this.productInfoRepository.save(productInfo);
        if (null == result) {
            log.error("【商品下架】下架商品失败，productInfo={}", productInfo);
            throw new SellException(ResultEnum.PRODUCT_UPDATE_FAIL);
        }
        return productInfo;
    }
}
